package com.wsc.frontier.database;

import java.sql.*;

public class MasterDB {
	Connection con;
	
	public boolean update(String tablename,String[] data,String time){
		try{
			Statement stmt;
			stmt = con.createStatement();
			String sql;
			if(time.equals("starttime")){
				sql = "SELECT * FROM `"+tablename+"` where ip = \'"+data[1]+"\'";
				ResultSet rs = stmt.executeQuery(sql);
				if(!rs.next()){
					return insert(tablename,data);
				}
				sql = "UPDATE `"+tablename+"` " +
		                   "SET name = \'"+data[0]+"\' , status = \'"+data[2]+"\'" +
		                   		" , starttime = \'"+data[3]+"\' , stoptime = \'---\' WHERE ip = \'"+data[1]+"\'";
			}
			else{
				sql = "UPDATE `"+tablename+"` "+
		                   "SET name = \'"+data[0]+"\' , status = \'"+data[2]+"\'" +
		                   		" , stoptime = \'"+data[4]+"\' WHERE ip = \'"+data[1]+"\'";
			}
		    
		      stmt.executeUpdate(sql);
		  	return true;
		}
		catch(Exception e){
			System.out.println("Exception is:"+e);
			return false;
		}
		
	}
	
	public boolean insert(String tablename,String[] data){
		try{
			PreparedStatement pst = con.prepareStatement("insert into `"+tablename+"` (`name`,`ip`,`status`,`starttime`,`stoptime`) values(?,?,?,?,?);");
			pst.setString(1, data[0]);
			pst.setString(2, data[1]);
			pst.setString(3, data[2]);
			pst.setString(4, data[3]);
			pst.setString(5, data[4]);
			pst.executeUpdate();
			return true;
		}
		catch(Exception e){
			System.out.println("Exception is:"+e);
			return false;
		}
	}

	public boolean getConnection(String url,String driver,String user,String password){
		try{
			Class.forName(driver);
		  	con=DriverManager.getConnection(url,user,password);
		  	return true;
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static void main(String s[]){
		MasterDB md = new MasterDB();
		String data[] = new String[5];
		data[0] = "controller";
		data[1] = "192.168.56.1";
		data[2] = "on";
		data[3] = "firsttime";
		data[4] = "stoptime";
		
	    if(md.getConnection("jdbc:mysql://localhost:3306/wscdb", "com.mysql.jdbc.Driver", "root", "herecomes")){
	    	System.out.println("got it");
	    }
	    else{
	    	System.out.println("mmmmmm");
	    }
	    if(md.update("masters", data,"starttime")){
	    	System.out.println("got it");
	    }
	    else{
	    	System.out.println("mmmmmm");
	    }
	    
	    data[0] = "controller";
		data[1] = "192.168.56.1";
		data[2] = "off";
		data[3] = "starttime";
		data[4] = "stoptime";
		if(md.update("masters", data,"stoptime")){
	    	System.out.println("got it");
	    }
	    else{
	    	System.out.println("mmmmmm");
	    }
		
	}
}
